import {Component} from 'react';

import CartItem from './cart-item';
import SettleAccount from './settle-account';

import './cart.css';

export default class Cart extends Component {
    state = {
        goods: [
            { id: 1234 , name: 'Huawei P50 Pocket' , price: 8988 , number: 5 },
            { id: 4321 , name: 'Redmi K50 Pro' , price: 2999 , number: 2 } ,
            { id: 2343 , name: '红魔7Pro 暗夜骑士' , price: 4799 , number: 1 },
            { id: 2565 , name: '中兴Axon 30 5G' , price: 2498 , number: 1 }
        ]
    }
    updateNumber = (id,number)=>{
        let p = this.state.goods.find( g => g.id === id ) ;
        if( p ) {
            p.number = number ;
        }
    }
    countTotal = ()=>{
        return this.state.goods.reduce( (prev,curr) => prev + curr.price * curr.number , 0 );
    }
    render(){
        return (
            <div className='cart'>
                { this.state.goods.map( g => <CartItem product={g} key={g.id} update={this.updateNumber} /> )}
                <SettleAccount total= { this.countTotal() } sum={ this.countTotal } />
            </div>
        );
    }
}